package ai.assist.admin.controller.system;

import com.anwen.mongo.model.PageResult;
import ai.assist.common.annotation.LogAnnotation;
import ai.assist.common.annotation.LogIgore;
import ai.assist.common.annotation.PassportSSO;
import ai.assist.common.businesss.mongo.entity.SysPermission;
import ai.assist.common.businesss.mongo.service.SysPermissionService;
import ai.assist.common.businesss.service.UserPermissionService;
import ai.assist.common.businesss.service.UserSessionService;
import ai.assist.common.context.PassportUserInfoContext;
import ai.assist.common.enums.ResponseCode;
import ai.assist.common.exception.BusinessException;
import ai.assist.common.utils.CachedBeanCopier;
import ai.assist.common.vo.admin.PermissionRespNode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Date;
import java.util.List;

/**
 * 菜单权限管理
 *
 * @version V1.0
 */
@RequestMapping("/sys/permission")
@RestController
@Api(tags = "权限管理", value = "菜单权限管理")
@PassportSSO
@CrossOrigin(originPatterns = "*", methods = {RequestMethod.GET, RequestMethod.POST})
public class PermissionController {

    @Autowired
    private SysPermissionService sysPermissionService;

    @Autowired
    private UserSessionService userSessionService;


    @Autowired
    private UserPermissionService userPermissionService;

    @PostMapping("del/{id}")
    @ApiOperation(value = "删除菜单权限接口")
    @LogAnnotation(title = "菜单权限管理", action = "删除菜单权限")
    public Object deleted(@PathVariable String id) {
        return sysPermissionService.removeByColumn("_id",id);//.lambdaUpdate().eq(SysPermission::getId,id).remove();
//        return true;
    }

    @PostMapping("/modify")
    @ApiOperation(value = "新增或更新菜单权限接口")
    @LogAnnotation(title = "菜单权限管理", action = "新增或更新菜单权限接口")
    public Object updatePermission(@RequestBody @Valid SysPermission dto) {
        if (dto.getId() == null) {
            verifyFormPid(dto);
            dto.setStatus(1);
            dto.setUpdateTime(new Date());
            dto.setCreateTime(new Date());
            return sysPermissionService.save(dto);
        }
        SysPermission sysPermission = sysPermissionService.lambdaQuery().eq(SysPermission::getId,dto.getId()).limitOne();
        if (null == sysPermission) {
            throw new BusinessException(ResponseCode.DATA_NOT_EXIST, "数据不存在");
        }
        dto.setUpdateTime(new Date());
        CachedBeanCopier.copyObject(dto,sysPermission);
        boolean update = sysPermissionService.updateById(sysPermission);
        if(update){
            userSessionService.refreshPermission(dto.getId());
        }
        return update;
    }

    @PostMapping("/{id}")
    @ApiOperation(value = "查询菜单权限接口")
    @LogAnnotation(title = "菜单权限管理", action = "查询菜单权限")
    @LogIgore
    public Object detailInfo(@PathVariable("id") String id) {
        return sysPermissionService.lambdaQuery().eq(SysPermission::getId,id).limitOne();
    }


    @PostMapping("/treeAll")
    @ApiOperation(value = "获取所有目录菜单树接口")
    @LogAnnotation(title = "菜单权限管理", action = "获取所有目录菜单树")
    @LogIgore
    public Object getAllPermissionTree() {
        List<PermissionRespNode> data = userPermissionService.selectAllByTree();
        PageResult<PermissionRespNode> page = new PageResult();
        page.setPageSize(1);
        page.setContentData(data);
        page.setPageNum(1);
        return page;
    }

    @PostMapping("/getMenuList")
    @ApiOperation(value = "获取当前用户菜单列表")
    @LogAnnotation(title = "用户管理", action = "获取当前用户菜单列表")
    @LogIgore
    public Object getMenuList() {
        return userPermissionService.permissionTreeList(PassportUserInfoContext.getContext().getId());
    }

    /**
     * 操作后的菜单类型是目录的时候 父级必须为目录
     * 操作后的菜单类型是菜单的时候，父类必须为目录类型
     * 操作后的菜单类型是按钮的时候 父类必须为菜单类型
     */
    private void verifyFormPid(SysPermission sysPermission) {
        SysPermission parent = sysPermissionService.getById(sysPermission.getPid());
        switch (sysPermission.getType()) {
            case 1:
                if (parent != null) {
                    if (parent.getType() != 1) {
                        throw new BusinessException("菜单类型是目录，所属菜单必须为默认顶级菜单或者目录");
                    }
                } else if (!StringUtils.isEmpty(sysPermission.getPid())) {
                    throw new BusinessException("操作后的菜单类型是目录，所属菜单必须为默认顶级菜单或者目录");
                }
                break;
            case 2:
                if (parent == null || parent.getType() != 1) {
                    throw new BusinessException("操作后的菜单类型是菜单，所属菜单必须为目录类型");
                }
                break;
            case 3:
                if (parent == null || parent.getType() != 2) {
                    throw new BusinessException("操作后的菜单类型是按钮，所属菜单必须为菜单类型");
                }
                if (StringUtils.isEmpty(sysPermission.getPerms())) {
                    throw new BusinessException("菜单权限的标识符不能为空");
                }
                break;
            default:
        }
    }
}
